<?php

namespace app\api\controller;

use app\services\ScenicAreaService;
use app\services\ScenicSpotService;
use app\services\UserScenicSpotService;
use support\Db;
use support\Request;

class ScenicController
{
    public static function areaDetail(Request $request)
    {
        try {
            $data = ScenicAreaService::detail(1);
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return e_rsp($e);
        }
    }

    public static function spotList(Request $request)
    {
        try {
            $page = $request->post('page', 1);
            $length = $request->post('length', 1000000);
            $name = $request->post('name');
            $order = $request->post('order', 1);

            switch ($order) {
                case 1:
                    $order = ['views', 'desc'];
                    break;
                case 2:
                    $order = ['created_time', 'desc'];
                    break;
            }

            $data = ScenicSpotService::list($page, $length, $name, $order);
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return e_rsp($e);
        }
    }

    public static function spotDetail(Request $request)
    {
        try {
            $id = $request->post('id');
            $lng = $request->post('lng', 0);
            $lat = $request->post('lat', 0);

            $data = ScenicSpotService::detail($id, $lng, $lat);
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return e_rsp($e);
        }
    }

    public static function view(Request $request)
    {
        Db::beginTransaction();
        try {
            $id = $request->post('id');
            $image = $request->post('image');

            if (empty($image)) {
                throw new \Exception('请上传打卡照片');
            }

            UserScenicSpotService::add($id, $image);

            Db::commit();
            return ok_rsp('成功');
        } catch (\Exception $e) {
            Db::rollBack();
            return e_rsp($e);
        }
    }

    public static function viewList(Request $request)
    {
        try {
            $page = $request->post('page', 1);
            $length = $request->post('length', 10);

            $data = UserScenicSpotService::list($page, $length);
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return e_rsp($e);
        }
    }

}